
from . import passport_blu
from flask import request, jsonify, current_app, make_response
from info.utils.response_code import RET
# 准备数据库
from info import redis_store
# 创造图形吗
from info.utils.captcha.captcha import captcha
from info import constants
import re
from info.models import User
import random
from info.libs.yuntongxun import sms
@passport_blu.route("/image_code")
def generate_image_code():
    image_code_id = request.args.get("image_code_id")
    if not image_code_id:
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    # 产生图片吗
    name, text, image = captcha.generate_captcha()
    print(text)
    try:
        redis_store.setex('ImageCode_'+image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, errmsg='保存验证码失败')
    else:
            response = make_response(image)
            response.headers['Content-Type'] = 'image/jpg'
            return response
@passport_blu.route("/sms_code",methods=["POST"])
def send_sms_code():
    mobile = request.json.get('mobile')
    image_code = request.json.get('image_code')
    image_code_id = request.json.get('image_code_id')
    print(image_code)
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    if not re.match(r'1[3456789]\d{9}', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号码不符合规则")
    try:
        real_image_code = redis_store.get('ImageCode_'+image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='或取图片验证码失败')
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码已经失效")
    try:
        redis_store.delete('ImageCode_'+image_code_id)
    except Exception as e:
        current_app.logger.error(e)

    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg="验证失败,不一致")
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询用户信息失败")
    else:
        if user is not None:
            return jsonify(errno=RET.DATAEXIST, errmsg="手机已经注册")
    sms_code = "06%d" % random.randint(0,999999)
    try:
        redis_store.setex('SMSCode_' + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存手机验证码失败')
    try:
        ccp = sms.CCP()
        result = ccp.send_template_sms(mobile,[sms_code, constants.SMS_CODE_REDIS_EXPIRES/60],1)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='发送验证码失败')
    if result == 0:
        return jsonify(errno=RET.OK, errmsg='发送成功')
    else:
        return jsonify(errno=RET.THIRDERR, errmsg='发送失败')






























